package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.pojo.UserThreadLocal;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.utils.RelativeDateFormat;
import com.tanhua.common.vo.PicUploadResult;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.pojo.Visitors;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.vo.CommentVo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.QuanZiVo;
import com.tanhua.server.vo.VisitorsVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

@Service
public class QuanZiService {
    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Autowired
    private UserService userService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private PicUploadService picUploadService;
    @Reference(version = "1.0.0")
    private VisitorsApi visitorsApi;


    public PageResult queryPublishList(String token, Integer page, Integer pageSize) {

        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        User user = UserThreadLocal.get();//拦截器放的
        PageInfo<Publish> publishPageInfo = quanZiApi.queryPublishList(user.getId(), page, pageSize);
        List<Publish> records = publishPageInfo.getRecords();
        pageResult.setItems(fillQuanZiVo(records));
        return pageResult;
    }

    public PageResult queryRecommendPublishList(String token, Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        User user = UserThreadLocal.get();//拦截器放的
        PageInfo<Publish> publishPageInfo = quanZiApi.queryRecommendPublishList(user.getId(), page, pageSize);
        List<Publish> records = publishPageInfo.getRecords();
        pageResult.setItems(fillQuanZiVo(records));
        return pageResult;
    }

    public String savePublish(String textContent, String location, String latitude, String longitude, MultipartFile[] multipartFile) {
        User user = UserThreadLocal.get();
        Publish publish = new Publish();
        publish.setUserId(user.getId());
        publish.setText(textContent);
        publish.setLocationName(location);
        publish.setLatitude(latitude);
        publish.setLongitude(longitude);
        publish.setSeeType(1);

        List<String> picUrls = new ArrayList<>();
        //图片上传
        for (MultipartFile file : multipartFile) {
            PicUploadResult picUploadResult = this.picUploadService.upload(file);
            picUrls.add(picUploadResult.getName());
        }

        publish.setMedias(picUrls);
        return this.quanZiApi.savePublish(publish);
    }

    private void fillUserInfoToQuanZiVo(UserInfo userInfo, QuanZiVo quanZiVo) {
        BeanUtil.copyProperties(userInfo, quanZiVo, "id");
        quanZiVo.setAvatar(userInfo.getLogo());
        quanZiVo.setNickname(userInfo.getNickName());
        quanZiVo.setGender(userInfo.getSex().name().toLowerCase());
        quanZiVo.setTags(StringUtils.split(userInfo.getTags(), ','));
        User user = UserThreadLocal.get();
        quanZiVo.setCommentCount(Convert.toInt(quanZiApi.queryCommentCount(quanZiVo.getId()))); //TODO 评论数
        quanZiVo.setDistance("1.2公里"); //TODO 距离
        quanZiVo.setHasLiked(quanZiApi.queryUserIsLike(user.getId(), quanZiVo.getId()) ? 1 : 0); // 是否点赞（1是，0否）
        quanZiVo.setLikeCount(Convert.toInt(quanZiApi.queryLikeCount(quanZiVo.getId()))); // 点赞数
        quanZiVo.setHasLoved(quanZiApi.queryUserIsLove(user.getId(), quanZiVo.getId()) ? 1 : 0); // 是否喜欢（1是，0否）
        quanZiVo.setLoveCount(Convert.toInt(quanZiApi.queryLoveCount(quanZiVo.getId()))); // 喜欢数
    }

    private List<QuanZiVo> fillQuanZiVo(List<Publish> records) {
        List<QuanZiVo> quanZiVos = new ArrayList<>();
        for (Publish record : records) {
            QuanZiVo quanZiVo = new QuanZiVo();

            quanZiVo.setId(record.getId().toHexString());
            quanZiVo.setUserId(record.getUserId());
            quanZiVo.setTextContent(record.getText());
            quanZiVo.setImageContent(record.getMedias().toArray(new String[]{}));
            quanZiVo.setCreateDate(RelativeDateFormat.format(new Date(record.getCreated())));
            quanZiVos.add(quanZiVo);
        }
        List<Object> userId = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfos = userInfoService.queryUserInfoByUserIdList(userId);
        for (QuanZiVo quanZiVo : quanZiVos) {
            for (UserInfo userInfo : userInfos) {
                if (quanZiVo.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    fillUserInfoToQuanZiVo(userInfo, quanZiVo);
                    break;
                }
            }
        }
        return quanZiVos;
    }

    public Long likeComment(String publishId) {
        User user = UserThreadLocal.get();
        Boolean bool = quanZiApi.likeComment(user.getId(), publishId);
        if (bool) {
            Long likeCount = quanZiApi.queryLikeCount(publishId);
            return likeCount;
        }
        return null;
    }

    public Long disLikeComment(String publishId) {
        User user = UserThreadLocal.get();
        Boolean bool = quanZiApi.disLikeComment(user.getId(), publishId);
        if (bool) {
            Long likeCount = quanZiApi.queryLikeCount(publishId);
            return likeCount;
        }
        return null;
    }

    public Long loveComment(String publishId) {
        User user = UserThreadLocal.get();
        Boolean bool = quanZiApi.loveComment(user.getId(), publishId);
        if (bool) {
            Long likeCount = quanZiApi.queryLoveCount(publishId);
            return likeCount;
        }
        return null;
    }

    public Long disLoveComment(String publishId) {
        User user = UserThreadLocal.get();
        Boolean bool = quanZiApi.disLoveComment(user.getId(), publishId);
        if (bool) {
            Long likeCount = quanZiApi.queryLoveCount(publishId);
            return likeCount;
        }
        return null;
    }

    public QuanZiVo queryById(String publishId) {
        User user = UserThreadLocal.get();
        Publish publish = quanZiApi.queryPublishById(publishId);
        if (publish == null) {
            return null;
        }
        return fillQuanZiVo(Arrays.asList(publish)).get(0);
    }

    public PageResult queryCommentList(String publishId, Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        User user = UserThreadLocal.get();
        PageInfo<Comment> pageInfo = quanZiApi.queryCommentList(publishId, page, pageSize);
        List<Comment> records = pageInfo.getRecords();
        if (CollUtil.isEmpty(records)) {
            return pageResult;
        }
        List<Object> userIdList = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfos = userInfoService.queryUserInfoByUserIdList(userIdList);
        List<CommentVo> commentVoList = new ArrayList<>();
        for (Comment record : records) {
            CommentVo commentVo = new CommentVo();
            commentVo.setId(record.getId().toHexString());
            commentVo.setContent(record.getContent());
            commentVo.setCreateDate(DateUtil.format(new Date(record.getCreated()), "HH:mm"));
            commentVo.setHasLiked(quanZiApi.queryUserIsLike(user.getId(), commentVo.getId()) ? 1 : 0);
            commentVo.setLikeCount(Convert.toInt(quanZiApi.queryLikeCount(commentVo.getId())));

            for (UserInfo userInfo : userInfos) {
                if (ObjectUtil.equal(userInfo.getId(), record.getUserId())) {
                    commentVo.setAvatar(userInfo.getLogo());
                    commentVo.setNickname(userInfo.getNickName());
                }
            }
            commentVoList.add(commentVo);
        }
        pageResult.setItems(commentVoList);
        return pageResult;
    }

    public Boolean saveComments(String publishId, String content) {
        User user = UserThreadLocal.get();
        return quanZiApi.saveComment(user.getId(), publishId, content);
    }

    public PageResult queryAlbumList(Long userId, Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        PageInfo<Publish> albumPageInfo = this.quanZiApi.queryAlbumList(userId, page, pageSize);
        List<Publish> records = albumPageInfo.getRecords();

        if (CollUtil.isEmpty(records)) {
            return pageResult;
        }

        List<QuanZiVo> quanZiVoList = new ArrayList<>();
        for (Publish record : records) {
            QuanZiVo quanZiVo = new QuanZiVo();

            quanZiVo.setId(record.getId().toHexString());
            quanZiVo.setImageContent(record.getMedias().toArray(new String[]{}));
            quanZiVo.setTextContent(record.getText());
            quanZiVo.setUserId(record.getUserId());
            quanZiVo.setCreateDate(RelativeDateFormat.format(new Date(record.getCreated())));

            quanZiVoList.add(quanZiVo);
        }

        List<Long> userIds = new ArrayList<>();
        for (QuanZiVo quanZiVo : quanZiVoList) {
            if (!userIds.contains(quanZiVo.getUserId())) {
                userIds.add(quanZiVo.getUserId());
            }

        }

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        List<UserInfo> userInfos = this.userInfoService.queryUserInfoList(queryWrapper);
        for (QuanZiVo quanZiVo : quanZiVoList) {
            for (UserInfo userInfo : userInfos) {
                if (quanZiVo.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    this.fillUserInfoToQuanZiVo(userInfo, quanZiVo);
                    break;
                }
            }
        }

        pageResult.setItems(quanZiVoList);

        return pageResult;
    }

    public List<VisitorsVo> queryVisitors() {
        User user = UserThreadLocal.get();

        List<Visitors> visitorsList = visitorsApi.queryMyVisitor(user.getId());
        if (CollUtil.isEmpty(visitorsList)) {
            return Collections.emptyList();
        }
        List<Object> userId = CollUtil.getFieldValues(visitorsList, "visitorUserId");
        List<UserInfo> userInfos = userInfoService.queryUserInfoByUserIdList(userId);
        List<VisitorsVo> visitorsVoList = new ArrayList<>();
        for (Visitors visitor : visitorsList) {
            for (UserInfo userInfo : userInfos) {
                if (ObjectUtil.equals(visitor.getVisitorUserId(), userInfo.getUserId())) {
                    VisitorsVo visitorsVo = new VisitorsVo();
                    visitorsVo.setAge(userInfo.getAge());
                    visitorsVo.setAvatar(userInfo.getLogo());
                    visitorsVo.setFateValue(visitor.getScore().intValue());
                    visitorsVo.setGender(userInfo.getSex().name().toLowerCase());
                    visitorsVo.setId(userInfo.getUserId());
                    visitorsVo.setNickname(userInfo.getNickName());
                    visitorsVo.setTags(StringUtils.split(userInfo.getTags(), ','));
                    visitorsVoList.add(visitorsVo);
                    break;
                }
            }
        }
        return visitorsVoList;
    }
}
